import { useEffect, useState } from 'react';
import { Card, Typography, Row, Col, Spin, Pagination, Layout, message } from 'antd';
import axios from 'axios';
import { Link } from 'react-router-dom';
import Sidebar from '../Sidebar.jsx';
import './index.css';

const { Meta } = Card;
const { Title, Text } = Typography;
const { Sider, Content } = Layout;

const Favorites = () => {
    const [favoriteArticles, setFavoriteArticles] = useState([]); // 默认值为空数组
    const [currentPage, setCurrentPage] = useState(1);
    const [loading, setLoading] = useState(true);
    const articlesPerPage = 12;

    useEffect(() => {
        const fetchFavorites = async () => {
            try {
                const userInfo = JSON.parse(localStorage.getItem('userInfo'));
                console.log('userInfo from localStorage:', userInfo);

                if (!userInfo || !userInfo.userId) {
                    message('请先登录');
                    return;
                }

                const userId = userInfo.userId;
                console.log('userId:', userId);

                // 获取用户所有的收藏记录
                const response = await axios.get(`/api/favorites/user/${userId}`);
                const favorites = response.data.data || []; // 如果 favorites 为 undefined 或 null，则设为 []

                // 获取每个收藏的文章信息
                const articlePromises = (favorites || []).map(async (favorite) => {
                    const articleResponse = await axios.get(`/api/articles/get/${favorite.article_id}`);
                    return {
                        ...favorite,
                        article: articleResponse.data,  // 把文章的详细信息合并到收藏数据中
                    };
                });

                const articlesWithDetails = await Promise.all(articlePromises);
                setFavoriteArticles(articlesWithDetails);
            } catch (error) {
                console.error('Error fetching favorites:', error);
                message.error('获取收藏失败，请稍后再试');
            } finally {
                setLoading(false);
            }
        };

        fetchFavorites();
    }, []);

    // 确保 favoriteArticles 是一个有效的数组
    const safeFavoriteArticles = Array.isArray(favoriteArticles) ? favoriteArticles : [];

    // 计算当前页面的文章索引
    const indexOfLastArticle = currentPage * articlesPerPage;
    const indexOfFirstArticle = indexOfLastArticle - articlesPerPage;

    // 通过过滤 favoriteArticles 数组来选择当前页面的数据
    const currentArticles = safeFavoriteArticles.filter((_, index) => {
        return index >= indexOfFirstArticle && index < indexOfLastArticle;
    });

    const paginate = (pageNumber) => setCurrentPage(pageNumber);

    return (
        <Layout style={{ minHeight: '100vh', background: '#f0f2f5' }}>
            <Sider width={240} style={{ background: '#FFFFFF',marginTop:'50px' }}>
                <Sidebar />
            </Sider>
            <Content style={{ margin: '24px 16px 0', overflow: 'initial' }}>
                <div className="favorites-container" style={{ padding: '24px', background: '#f7f7fb', borderRadius: '12px' }}>
                    <Title level={2} style={{ textAlign: 'center', color: '#211f3f' }}>
                        我的收藏
                    </Title>

                    {loading ? (
                        <Spin size="large" style={{ margin: '0 auto', display: 'block' }} />
                    ) : (
                        <>
                            {safeFavoriteArticles.length === 0 ? (
                                <div style={{ textAlign: 'center', color: '#7f8c8d' }}>
                                    <Text>暂无收藏的文章</Text>
                                </div>
                            ) : (
                                <>
                                    <Row gutter={[16, 16]} justify="center" className="row-of-cards">
                                        {currentArticles.map((favorite) => {
                                            const article = favorite.article;
                                            return article ? (
                                                <Col key={favorite.favorite_id} xs={24} sm={12} md={8} lg={6} xl={6} className="card-item">
                                                    <Link to={`/reading/article/${article.article_id}`} style={{ textDecoration: 'none' }}>
                                                        <Card
                                                            bordered={false}
                                                            bodyStyle={{ padding: '24px', background: '#f7f7f7'  }}
                                                            hoverable
                                                            className="small-card"
                                                        >
                                                            <Meta
                                                                title={<Text style={{ color: '#211f3f' }}>{article.title}</Text>}
                                                                description={article.original_text?.slice(0, 100) || '暂无内容'}
                                                            />
                                                        </Card>
                                                    </Link>
                                                </Col>
                                            ) : null;
                                        })}
                                    </Row>
                                    <Pagination
                                        current={currentPage}
                                        total={safeFavoriteArticles.length}
                                        pageSize={articlesPerPage}
                                        onChange={paginate}
                                        showSizeChanger={false}
                                        style={{ textAlign: 'center', marginTop: '20px' }}
                                    />
                                </>
                            )}
                        </>
                    )}
                </div>
            </Content>
        </Layout>
    );
};

export default Favorites;